import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import '../services/bluetooth_service.dart';
import '../services/permission_service.dart';

class BluetoothDeviceScreen extends StatefulWidget {
  const BluetoothDeviceScreen({super.key});

  @override
  State<BluetoothDeviceScreen> createState() => _BluetoothDeviceScreenState();
}

class _BluetoothDeviceScreenState extends State<BluetoothDeviceScreen> {
  final BluetoothService _bluetoothService = BluetoothService();
  final PermissionService _permissionService = PermissionService();
  bool _isScanning = false;

  @override
  void initState() {
    super.initState();
    _checkPermissionsAndStartScan();
  }

  Future<void> _checkPermissionsAndStartScan() async {
    bool permissionsGranted = await _permissionService.requestBluetoothPermissions(context);
    if (permissionsGranted) {
      _startScan();
    }
  }

  Future<void> _startScan() async {
    setState(() {
      _isScanning = true;
    });
    
    await _bluetoothService.startScan();
    
    // 4秒后自动停止扫描
    Future.delayed(const Duration(seconds: 4), () {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
        _bluetoothService.stopScan();
      }
    });
  }

  Future<void> _connectToDevice(BluetoothDevice device) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );

    try {
      await _bluetoothService.connectToDevice(device);
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        Navigator.of(context).pop(); // 返回上一页
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('连接失败'),
              content: Text('无法连接到设备: ${e.toString()}'),
              actions: <Widget>[
                TextButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    }
  }

  Widget _buildDeviceItem(BluetoothDevice device) {
    return ListTile(
      title: Text(device.name.isEmpty ? '未知设备' : device.name),
      subtitle: Text(device.id.toString()),
      trailing: StreamBuilder<BluetoothDeviceState>(
        stream: device.state,
        initialData: BluetoothDeviceState.disconnected,
        builder: (c, snapshot) {
          if (snapshot.data == BluetoothDeviceState.connected) {
            return const Icon(Icons.bluetooth_connected);
          }
          return Text('${device.rssi} dBm');
        },
      ),
      onTap: () => _connectToDevice(device),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择设备'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _isScanning ? null : _checkPermissionsAndStartScan,
          ),
        ],
      ),
      body: StreamBuilder<List<ScanResult>>(
        stream: _bluetoothService.scanResults,
        initialData: const [],
        builder: (c, snapshot) {
          if (_isScanning) {
            return const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('正在扫描设备...'),
                ],
              ),
            );
          }

          if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('未发现设备'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _checkPermissionsAndStartScan,
                    child: const Text('重新扫描'),
                  ),
                ],
              ),
            );
          }

          return ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              return _buildDeviceItem(snapshot.data![index].device);
            },
          );
        },
      ),
    );
  }
} 